﻿using Repository.Core.Models.Dto;
using Repository.Core.Models.Queries;
using Repository.Core.Models.VO;
using Repository.Core.Providers;
using MiniFox.Components;
using MiniFox.Infrastructure;
using MiniFox.Platform.Applications;
using MiniFox.Platform.Applications.Auth;
using MiniFox.Platform.Exceptions;
using MiniFox.Utility;

namespace Repository.Core.Services.Impls
{
    [AutoResolve]
    public class VersionService : VersioningServiceBase, IVersionService
    {
        [AutoWired]
        protected IVersionProvider Provider { get; set; }

        public VersionService(string repoName, SystemPrincipal principal) : base(repoName, principal)
        {
        }

        public ResultObject<IEnumerable<VersionSetVo>> Query(PagedQueryObject<CommonQuery> request)
        {
            var result = Provider.Query(this.RepoName, request);
            return result;
        }

        public ResultObject<IEnumerable<VersionItemVo>> VersionItems(string versionSetName, PagedQueryObject<VersionQuery> request)
        {
            var result = Provider.VersionItems(this.RepoName, versionSetName, request);
            return result;
        }

        public void CheckOut(string versionSetName)
        {
            if (!Provider.CheckOut(this.RepoName, this.Identity, versionSetName))
                throw new PlatformException("ERR_OperateFail");
        }

        public void Commit(CommitDto dto)
        {
            if (!Provider.Commit(this.RepoName, this.Identity, dto))
                throw new PlatformException("ERR_OperateFail");
        }

        public VersionItemVo Pull(string versionSetName, long? versionId)
        {
            if (!Provider.Pull(this.RepoName, this.Identity, versionSetName, versionId))
                return null;
            return Provider.GetItem(this.RepoName, versionSetName, versionId);
        }

        public object GetItemContent(string versionSetName, long versionId)
        {
            var content = Provider.GetItemContent(this.RepoName, versionSetName, versionId);
            if (content == null) return null;
            return content.ToJsonObject();
        }

        public void Sync()
        {
            if (!Provider.Sync(this.RepoName, this.Identity))
                throw new PlatformException("ERR_OperateFail");
        }

        public virtual T GetItemObject<T>(string versionSetName, long versionId)
        {
            var content = Provider.GetItemContent(this.RepoName, versionSetName, versionId);
            return content.ToJsonObject<T>();
        }
    }
}
